#!/bin/sh

. $TESTSUITE_LIB_UTILS
. $(dirname $0)/find-docker.sh

# use ramdrive for ydb if available
RAMDISK="/ramdrive/$USER"
if mkdir -p "$RAMDISK" 2> /dev/null; then
    YDB_TMPDIR=$RAMDISK/_ydb${WORKER_SUFFIX_PATH}
fi

if [ "x$YDB_TMPDIR" = "x" ]; then
    die "YDB_TMPDIR must be set or RAM-disk must be enabled"
fi
if [ "x$YDB_GRPC_PORT" = "x" ]; then
    die "YDB_GRPC_PORT must be set"
fi
if [ "x$YDB_GRPC_TLS_PORT" = "x" ]; then
    die "YDB_GRPC_TLS_PORT must be set"
fi
if [ "x$YDB_MON_PORT" = "x" ]; then
    die "YDB_MON_PORT must be set"
fi
if [ "x$YDB_HOSTNAME" = "x" ]; then
    die "YDB_HOSTNAME must be set"
fi
if [ "x$YDB_CONTAINER_NAME" = "x" ]; then
    die "YDB_CONTAINER_NAME must be set"
fi
if [ "x$YDB_DOCKER_IMAGE" = "x" ]; then
    die "YDB_DOCKER_IMAGE must be set"
fi

YDB_DATA_DIR=$YDB_TMPDIR/data

export GRPC_PORT="$YDB_GRPC_PORT"
export GRPC_TLS_PORT="$YDB_GRPC_TLS_PORT"
export MON_PORT="$YDB_MON_PORT"
export YDB_HOSTNAME="$YDB_HOSTNAME"

start_ydb() {
    mkdir -p "$YDB_DATA_DIR"
    $DOCKER_BINPATH run --rm -d --name ${YDB_CONTAINER_NAME} -h ${YDB_HOSTNAME} \
            -p ${YDB_GRPC_TLS_PORT}:${YDB_GRPC_TLS_PORT} \
            -p ${YDB_GRPC_PORT}:${YDB_GRPC_PORT} \
            -p ${YDB_MON_PORT}:${YDB_MON_PORT} \
            -e GRPC_TLS_PORT=$YDB_GRPC_TLS_PORT \
            -e GRPC_PORT=$YDB_GRPC_PORT \
            -e MON_PORT=$YDB_MON_PORT \
            ${YDB_DOCKER_IMAGE}
}

start() {
    start_ydb
}

stop() {
    $DOCKER_BINPATH stop ${YDB_CONTAINER_NAME}
    rm -rf "$YDB_TMPDIR"
}

script_main "$@"
